import os
from io import BytesIO
import base64

from PIL import Image  # Install with: pip install pillow

from google import genai
from google.genai import types

import openai


import os
import glob

openai.api_key = ""
openai.api_base = "https://api.deepseek.com/beta"

def translate_text(text, source_lang='zh', target_lang='en'):

    prompt = f"将以下{source_lang}文本翻译为{target_lang}：\n{text}"

    # 调用 DeepSeek 模型
    response1 = openai.Completion.create(
        model="deepseek-chat",
        prompt=prompt,
        max_tokens=1000,
        n=1,
        stop=None,
        temperature=0.5,
    )
    # 提取并返回翻译结果
    return response1.choices[0].text.strip()



def get_latest_txt_file(folder_path):
    """
    获取文件夹下最新的 TXT 文件
    :param folder_path: 文件夹路径
    :return: 最新文件的路径，如果没有 TXT 文件则返回 None
    """
    # 获取文件夹下所有的 TXT 文件
    txt_files = glob.glob(os.path.join(folder_path, "*.txt"))

    # 如果没有找到 TXT 文件，返回 None
    if not txt_files:
        print(f"文件夹 '{folder_path}' 中没有找到 TXT 文件！")
        return None

    # 找到最新的文件（按修改时间排序）
    latest_file = max(txt_files, key=os.path.getmtime)
    return latest_file

def read_file(file_path):
    """
    读取文件内容，去除空行和换行符，并在最后添加一句话
    :param file_path: 文件路径
    :return: 处理后的文件内容
    """
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            # 读取文件内容并去除空行和换行符
            content = file.read()
            content = content.replace('\n', ' ')  # 替换换行符为空格
            content = ' '.join(content.split())   # 去除多余的空格

            # 在文件内容最后添加一句话
            content += " 帮我换一身符合上述要求的衣服。"

            return content  # 返回处理后的内容
    except Exception as e:
        print(f"读取文件时发生错误：{e}")
        return None

def get_latest_image_file(folder_path):
    """
    获取文件夹下最新的图片文件
    :param folder_path: 文件夹路径
    :return: 最新图片文件的路径，如果没有图片文件则返回 None
    """
    # 支持的图片文件扩展名
    image_extensions = ["*.jpg", "*.jpeg", "*.png", "*.gif", "*.bmp", "*.webp"]

    # 获取文件夹下所有的图片文件
    image_files = []
    for ext in image_extensions:
        image_files.extend(glob.glob(os.path.join(folder_path, ext)))

    # 如果没有找到图片文件，返回 None
    if not image_files:
        print(f"文件夹 '{folder_path}' 中没有找到图片文件！")
        return None

    # 找到最新的文件（按修改时间排序）
    latest_file = max(image_files, key=os.path.getmtime)
    return latest_file


def main():

    folder_path = r"D:\BTJFProject\Fitting\backend\params"
    # 获取最新的 TXT 文件
    latest_txt_file = get_latest_txt_file(folder_path)
    chinese_text = read_file(latest_txt_file)
    english_text = translate_text(chinese_text)

    # Use the previously generated image
    folder_path = r"D:\BTJFProject\Fitting\backend\uploads"
    latest_image_file = get_latest_image_file(folder_path)
    image = Image.open(latest_image_file)

    # Convert the image to bytes
    image_bytes = BytesIO()
    image.save(image_bytes, format='PNG')
    image_bytes = image_bytes.getvalue()

    client = genai.Client(api_key=os.getenv("GEMINI_API_KEY"))

    #text_input = 'Hello, this is a picture of me wearing clothes. Can you help me change into a new outfit and wear winter clothes?'
    text_input = english_text
    # Create proper content structure with image part
    contents = [
        {
            "parts": [
                {"text": text_input},
                {
                    "inline_data": {
                        "mime_type": "image/png",
                        "data": base64.b64encode(image_bytes).decode('utf-8')
                    }
                }
            ]
        }
    ]

    response = client.models.generate_content(
        model="gemini-2.0-flash-exp-image-generation",
        contents=contents,
        config=types.GenerateContentConfig(
        response_modalities=['Text', 'Image']
        )
    )

    for part in response.candidates[0].content.parts:
        if part.text is not None:
            print(part.text)
        elif part.inline_data is not None:
            image = Image.open(BytesIO(part.inline_data.data))
            image.save(r'D:\BTJFProject\Fitting\backend\results\gemini-edited-image.png')

if __name__ == "__main__":
    main()